from epics import PV
import multiprocessing as mp
from PV_publish import run_pv_publish
from connect_db import get_data
import time
import re
# 此处定义SQlite数据库与IOC数据库的关联
# 格式{"device name":"pv name"}
pv_dict = {'南墙': "TEST11111", '靶尾': "TEST2", '料罐头': "TEST3", '料罐尾': "TEST4",
           '东墙': "TEST5", '隧道入口': "TEST6", '靶头': "TEST7", '电磁泵': "TEST8", '北墙': "TEST9"}


def data_format(db_data: list):
    result = {}
    db_data.reverse()
    for tup in db_data:
        deviceId = re.sub("\x00", "", tup[0])
        data = re.sub("\x00", "", tup[1]).split()
        if not deviceId == "":
            result[deviceId] = float(data[0])
    return result


if __name__ == "__main__":

    p1 = mp.Process(target=run_pv_publish, args=(pv_dict,))
    p1.start()
    time.sleep(1)

    pv = {pvname: PV(pvname) for pvname in pv_dict.values()}
    while True:
        time.sleep(1)
        pv_data = data_format(get_data(length=100))
        for deviceId, data in pv_data.items():
            pv[pv_dict[deviceId]].put(data)
            time.sleep(0.01)
        print([pv.get() for pv in pv.values()])
